package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.ElasticConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam searchParam) {
        // 准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        SearchResult searchResult = null;
        try {
            // 执行检索
            SearchResponse searchResponse = client.search(searchRequest, ElasticConfig.COMMON_OPTIONS);

            // 分析返回结果，封装成我们需要的数据
            searchResult = buildSearchResult(searchParam, searchResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    /**
     * 构建检索请求
     *
     * @param searchParam
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();
        /**
         * 查询：模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 按照标题模糊匹配，进行查询
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            boolQuery.must(
                    QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword())
            );
        }
        // 按照3级分类ID，进行查询
        if (!ObjectUtils.isEmpty(searchParam.getCatalog3Id())) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        // 按照品牌ID，进行查询
        if (!CollectionUtils.isEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        // 按照所有指定的属性，进行查询 attrs=1_其他:安卓&attrs=2_屏幕尺寸:5寸:6寸
        if (!CollectionUtils.isEmpty(searchParam.getAttrs())) {
            for (String attr : searchParam.getAttrs()) {
                //attrs=2_屏幕尺寸:5寸:6寸
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] attrItem = attr.split("_");
                String attrId = attrItem[0];
                String[] attrValues = attrItem[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个都得必须生成一个nestedQuery
                boolQuery.filter(
                        QueryBuilders.nestedQuery(
                                "attrs",
                                nestedBoolQuery,
                                ScoreMode.None
                        )
                );
            }
        }
        // 按照库存是否有，进行查询
        if (searchParam.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }
        // 按照价格区间，进行查询 skuPrice=1_500 _500 500_
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            RangeQueryBuilder skuPriceRange = QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchParam.getSkuPrice().split("_");
            if (s.length == 2) {
                // 区间 1_500 这种情况
                skuPriceRange.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (searchParam.getSkuPrice().startsWith("_")) {
                    // _500 这种情况
                    skuPriceRange.lte(s[0]);
                } else if (searchParam.getSkuPrice().endsWith("_")) {
                    // 0_ 这种情况
                    skuPriceRange.gte(s[0]);
                }
            }
            boolQuery.filter(skuPriceRange);
        }
        searchSourceBuilder.query(boolQuery);

        /**
         * 排序，分页，高亮
         */
        // 排序 sort=saleCount_asc/desc
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            String[] s = searchParam.getSort().split("_");
            String field = s[0];
            String sortType = s[1];
            SortOrder sortOrder = sortType.equalsIgnoreCase("asc")
                    ? SortOrder.ASC
                    : SortOrder.DESC;
            searchSourceBuilder.sort(field, sortOrder);
        }
        // 分页   (pageNum - 1) * pageSize
        searchSourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);
        // 高亮 只有查了名字才显示高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            searchSourceBuilder.highlighter(
                    SearchSourceBuilder.highlight()
                            .field("skuTitle")
                            .preTags("<b style='color:red;'>")
                            .postTags("</b>")
            );
        }

        /**
         * 聚合分析
         */
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders
                .terms("brand_agg")
                .field("brandId")
                .size(50)
                .subAggregation(
                        AggregationBuilders
                                .terms("brand_name_agg")
                                .field("brandName")
                                .size(1))
                .subAggregation(
                        AggregationBuilders
                                .terms("brand_img_agg")
                                .field("brandImg")
                                .size(1));
        searchSourceBuilder.aggregation(brandAgg);

        // 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders
                .terms("catalog_agg")
                .field("catalogId")
                .size(50)
                .subAggregation(
                        AggregationBuilders
                                .terms("catalog_id_agg")
                                .field("catalogId")
                                .size(20))
                .subAggregation(
                        AggregationBuilders
                                .terms("catalog_name_agg")
                                .field("catalogName")
                                .size(1));
        searchSourceBuilder.aggregation(catalogAgg);

        // 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders
                .nested("attr_agg", "attrs")
                .subAggregation(
                        AggregationBuilders
                                .terms("attr_id_agg")
                                .field("attrs.attrId")
                                .size(20)
                                .subAggregation(
                                        AggregationBuilders
                                                .terms("attr_name_agg")
                                                .field("attrs.attrName")
                                                .size(1))
                                .subAggregation(
                                        AggregationBuilders
                                                .terms("attr_value_agg")
                                                .field("attrs.attrValue")
                                                .size(50))
                );
        searchSourceBuilder.aggregation(attrAgg);
        log.debug("构建的dsl: {}", searchSourceBuilder.toString());
        return new SearchRequest(
                new String[]{EsConstant.PRODUCT_INDEX},
                searchSourceBuilder
        );
    }

    /**
     * 构建结果数据
     *
     * @param searchResponse
     * @return
     */
    private SearchResult buildSearchResult(SearchParam searchParam, SearchResponse searchResponse) {
        SearchResult searchResult = new SearchResult();

        SearchHits hits = searchResponse.getHits();
        // 返回的所有商品
        List<SkuEsModel> productList = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                SkuEsModel skuEsModel = JSON.parseObject(hit.getSourceAsString(), SkuEsModel.class);
                // 设置高亮信息
                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField highlightField = hit.getHighlightFields().get("skuTitle");
                    String skuTitle = highlightField.getFragments()[0].toString();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                productList.add(skuEsModel);
            }
        }
        searchResult.setProducts(productList);


        // 当前商品所有涉及到的属性信息
        ParsedNested attr_agg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            // 获取分析数据
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            long attrId = bucket.getKeyAsNumber().longValue();
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            List<String> attrValues = attr_value_agg
                    .getBuckets()
                    .stream()
                    .map(item -> item.getKeyAsString())
                    .collect(Collectors.toList());

            // 封装数据
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);


        // 当前商品所有涉及到的品牌信息
        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            // 获取分析数据
            long brandId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");

            // 封装数据
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brand_name_agg.getBuckets().get(0).getKeyAsString());
            brandVo.setBrandImg(brand_img_agg.getBuckets().get(0).getKeyAsString());
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        // 当前商品所有涉及到的分类信息
        ParsedLongTerms catalog_agg = searchResponse.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            // 获取分析数据
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            long catalogId = bucket.getKeyAsNumber().longValue();
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();

            // 封装数据
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(catalogId);
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);

        // 分页相关
        long total = hits.getTotalHits().value;
        long totalPages = total / EsConstant.PRODUCT_PAGE_SIZE;
        if (total % EsConstant.PRODUCT_PAGE_SIZE != 0) {
            totalPages++;
        }
        searchResult.setPageNum(searchParam.getPageNum());
        searchResult.setTotal(total);
        searchResult.setTotalPages((int) totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);

        log.debug("搜索结果数据: {}", searchResult);
        return searchResult;
    }

}
